package kr.hkit.powerjava.chapter26;
//PDF 134p
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

//PDF 134p
public class DBProperties {

	public static Properties loadPropertis(String propertiesFile) {
		BufferedInputStream bis = null;
		Properties prop = null;

		try {
			bis = new BufferedInputStream(new FileInputStream(propertiesFile));
			prop = new Properties();
			// 읽은 정보 가져오기
			prop.loadFromXML(bis);
		} catch (FileNotFoundException e) {
			System.err.print("파일이 존재하지 않음");
		} catch (InvalidPropertiesFormatException e) {
			System.err.print("유효하지 않은 파일");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				try {
					bis.close();
					bis = null;
				} catch (Exception e) {
			}
		}
		return prop;
	}

	// savePropertis("test.prof", "user", "pass", "db"); //value란 이름의 배열로 담겨짐
	// 내용 공개안함
	public static void savePropertis(String propertiesFile, String... value) {
		BufferedOutputStream bos = null;
		Properties prop = null;

		try {
			bos = new BufferedOutputStream(new FileOutputStream(propertiesFile));
			prop = new Properties();
			// 여기에 정보 넣음
			// 암호화해서 해야됨...... value값
			prop.setProperty("DRIVER", value[0]); //키 값 밸류값
			prop.setProperty("URL", value[1]);
			prop.setProperty("USER", value[2]);
			prop.setProperty("PASSWORD", value[3]);
			
			prop.storeToXML(bos, "DataBase Connection XML Property File"); // xml형태로 저장
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bos != null)
				try {
					bos.close();
					bos = null; //확실하게!! 
				} catch (Exception e) {
			}
		}
	}

	public static void prnProperties(Properties prop) { // 출력
		Set<Entry<Object, Object>> setmap = prop.entrySet();
		
		for(Entry<Object, Object> propty : setmap) {
			System.out.printf("%s : %s\n", propty.getKey(), propty.getValue());
		}
	}
}
